#include "gwlib/gw_statfs.h"

#include <json/json.h>
#include <gwbase/curl_wrapper.h>
#include <gwbase/base/logging.h>
#include "gwlib/gw_login.h"

namespace dicom {

static bool ParseSpaceInfo(const std::string& response,
                           GwSpaceInfo* info)
{
  Json::Reader r;
  Json::Value v;
  if (r.parse(response, v, false) == false) {
    LOG_ERROR << "failed to parse json response: " << response;
    return false;
  }

  if (v["code"].asInt() != 0) {
    LOG_ERROR << "result code is not zero: " << v["code"].asInt();
    return false;
  }

  Json::Value& stat = v["stat"];

  info->allSpace = stat["allSpace"].asInt64();
  info->usedSpace = stat["usedSpace"].asInt64();
  info->allNonFileSpace = stat["allNonFileSpace"].asInt64();
  info->singleNonFileSize = stat["singleNonFileSize"].asInt64();

  info->cacheTotalSpace = stat["cacheSpace"].asInt64();
  info->cacheUsedSpace = stat["cacheUsed"].asInt64();
  info->cacheRemovableSpacek = stat["cacheRemovable"].asInt64();
  return true;
}

int GetGwSpaceInfo(GwToken* t,
                   GwSpaceInfo* info)
{
  EasyCurl curl;

  CurlHeaders headers;
  headers.AddOAuthHeader(t->token);
  curl.AddHeaders(&headers);

  std::string url = t->server + "/api/statfs";
  curl.SetUrl(url);

  std::string response;
  curl.EnableDebugOutput(true);
  bool ok = curl.PerformText(&response);
  if (!ok || curl.http_status() != 200)
    return -1;

  LOG_INFO << response;
  if (!ParseSpaceInfo(response, info))
    return -1;

  return 0;
}
}
